﻿using System;
using System.Text;
using System.Windows.Forms;

namespace QAToolsAddin.GenericDialogs.Fields {
    class FieldCheckBoxes : Field, IField {
        readonly Panel _control;

        public FieldCheckBoxes(string name, string info, string[] labels, bool[] checkedItems, bool retore = false)
            : base(name, info, retore) {
            _control = new Panel {
                Height = 22
            };
            for (int i = 0; i < labels.Length; i++) {
                _control.Controls.Add(new CheckBox {
                    AutoSize = true,
                    Checked = checkedItems[i],
                    Text = labels[i]
                });
            }
            _control.Resize += control_Resize;
        }

        public override Control Control {
            get { return _control; }
        }

        public bool[] Value {
            get {
                int nbControls = _control.Controls.Count;
                var checkedItems = new bool[nbControls];
                for (int i = 0; i < nbControls; i++)
                    checkedItems[i] = ((CheckBox)_control.Controls[i]).Checked;
                return checkedItems;
            }
            set {
                for (int i = 0; i < _control.Controls.Count; i++)
                    ((CheckBox)_control.Controls[i]).Checked = value[i];
            }
        }

        object IField.Value {
            get { return Value; }
            set { Value = (bool[])value; }
        }

        public bool GetValue(int index) {
            return ((CheckBox)_control.Controls[index]).Checked;
        }

        public override string ToDebugString() {
            var sb = new StringBuilder(base.Label + ":");
            foreach (CheckBox bt in _control.Controls)
                sb.Append(" " + bt.Text + "=" + bt.Checked.ToString());
            return sb.ToString();
        }

        private void control_Resize(object sender, EventArgs e) {
            int len = _control.Controls.Count;
            int top = (_control.Height - _control.Controls[0].Height) / 2 + 1;
            for (int i = 0; i < len; i++) {
                _control.Controls[i].Left = i == 0 ? 0 : _control.Controls[i - 1].Left + _control.Controls[i - 1].Width;
                _control.Controls[i].Top = top;
            }
        }
    }
}
